﻿<template>
    <full-screen-dialog
        :title="titleMap[mode]"
        v-model="visible"
        :width="1200"
        destroy-on-close
        :close-on-click-modal="false"
        :before-close="handleBeforeClose"
    >
        <el-form
            :model="entityObj"
            :rules="rules"
            :disabled="mode == 'Show'"
            ref="dialogForm"
            label-width="100px"
        >
            <el-row>
                <div class="w25pr30">
                    <el-form-item label-width="120px" label="要货时间" prop="applyDate">
                        <el-date-picker
                            v-model="entityObj.applyDate"
                            type="datetime"
                            value-format="YYYY-MM-DD"
                            format="YYYY-MM-DD"
                            placeholder="请输入要货时间"
                            style="width: 100%;margin-left: 9px;"
                        />
                    </el-form-item>
                </div>
                <div class="w25pr30">
                    <el-form-item label-width="120px" label="期望到货时间">
                        <el-date-picker
                            v-model="entityObj.expectedDate"
                            type="datetime"
                            value-format="YYYY-MM-DD"
                            format="YYYY-MM-DD"
                            placeholder="请输入要货时间"
                            style="width: 100%"
                        />
                    </el-form-item>
                </div>
                <div class="w25pr30">
                    <el-form-item label-width="120px" label="要货单位" prop="storeId">
                        <el-tooltip placement="top" style="width: 80%" v-if="orgType == 2">
                            <template #content>
                                联系人: {{ entityObj.realName }}
                                <br />
                                联系电话:{{ entityObj.mobile }}
                                <br />
                                收货地址:{{ entityObj.address }}
                            </template>
                            <el-input disabled v-model="entityObj.storeName" style="width: 100%" />
                        </el-tooltip>

                        <sc-apply-org-select
                            v-else
                            ref="storeSelect"
                            :props="storeProps"
                            :selectKeyValue="'storeId'"
                            :multiple="false"
                            :defaultQueryList="{ purchaseUnityId: entityObj.purchaseUnityId }"
                            v-model="entityObj.stores"
                            @fatherMethod="storeSelectProcess"
                        ></sc-apply-org-select>
                    </el-form-item>
                </div>
                <div class="w25">
                    <el-form-item label-width="120px" label="供货单位" prop="purchaseUnityId">
                        <!-- <sc-purchase-unity-select
                            placeholder="---请选择采购单位---"
                            ref="purchaseUnitySelect"
                            :props="purchaseUnityProps"
                            :selectKeyValue="'purchaseUnityId'"
                            v-model="entityObj.purchaseUnitys"
                            :defaultQueryList="{storeId:this.entityObj.storeId}"
                            @fatherMethod="purchaseUnitySelectProcess"
                            :multiple="false"
                            v-if="orgType==2"
                        ></sc-purchase-unity-select>-->
                        <el-tooltip placement="top">
                            <template #content>
                                联系人: {{ entityObj.purchaseRealName }}
                                <br />
                                联系电话:{{ entityObj.purchaseMobile }}
                                <br />
                                联系地址:{{ entityObj.purchaseAddress }}
                                <br />
                            </template>
                            <el-input
                                disabled
                                v-model="entityObj.purchaseUnityName"
                                style="width: 100%"
                            />
                        </el-tooltip>
                    </el-form-item>
                </div>
            </el-row>
            <el-row>
                <el-col :span="12" style="margin-left: 10px;">
                    <el-form-item label-width="120px" label="行操作">
                        <el-button
                            type="primary"
                            icon="el-icon-plus"
                            size="mini"
                            @click="handleAddDetails"
                        >添加</el-button>
                        <el-button
                            type="primary"
                            icon="el-icon-delete"
                            size="mini"
                            @click="handleDeleteDetails"
                        >删除</el-button>
                        <el-button
                            type="primary"
                            icon="el-icon-delete"
                            size="mini"
                            @click="handleDeleteAllDetails"
                        >清空</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="110px">
                        <el-table
                            :loading="isSaveing"
                            :data="entityObj.applyOrderItems"
                            border
                            style="width: 100%"
                            @selection-change="handleDetailSelectionChange"
                            :row-class-name="rowClassName"
                            ref="tb"
                        >
                            <el-table-column type="selection" width="30" align="center" />
                            <el-table-column label="物料名称" min-width="160">
                                <template #default="scope">
                                    <el-input
                                        v-model="scope.row.materialName"
                                        autocomplete="off"
                                        placeholder="请输入物料名称"
                                        @blur="handleMaterial(scope.row,scope.$index)"
                                        style="width: 100%"
                                        :disabled="scope.row.materialItemId"
                                    ></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column label="规格" min-width="130">
                                <template #default="scope">
                                    <el-input
                                        v-model="scope.row.materialSpecs"
                                        autocomplete="off"
                                        placeholder="请输入规格"
                                        style="width: 100%"
                                        :disabled="scope.row.materialItemId"
                                    ></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column label="物料类别" min-width="130">
                                <template #default="scope">
                                    <el-tree-select
                                        placeholder="---请选择物料分类---"
                                        v-model="scope.row.materialTypeId"
                                        :props="{ label: 'label', value: 'value', children: 'children' }"
                                        collapse-tags
                                        collapse-tags-tooltip
                                        :data="materialTypeTree"
                                        :multiple="false"
                                        :render-after-expand="false"
                                        :disabled="scope.row.materialItemId"
                                        style="width: 100%"
                                    />
                                </template>
                            </el-table-column>
                            <el-table-column label="单位" min-width="85">
                                <template #default="scope">
                                    <el-form-item>
                                        <el-select
                                            placeholder="---请选择单位---"
                                            v-model="scope.row.unitCode"
                                            :disabled="scope.row.materialItemId"
                                            style="width: 100%"
                                        >
                                            <el-option
                                                v-for="item in optionsUnit"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.value"
                                            />
                                        </el-select>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column label="数量" min-width="130" prop="qty">
                                <template #default="scope">
                                    <el-input-number
                                        v-model="scope.row.qty"
                                        style="width: 100%"
                                        :step="1"
                                        :min="1"
                                        controls-position="right"
                                    ></el-input-number>
                                </template>
                            </el-table-column>
                            <el-table-column label="要货总价" min-width="110">
                                <template #default="scope">
                                    <el-input-number
                                        v-model="scope.row.applyTotalAmount"
                                        type="number"
                                        :min="0.01"
                                        :step="0.01"
                                        placeholder="请输入配送总价"
                                        controls-position="right"
                                        style="width: 100%"
                                    />
                                </template>
                            </el-table-column>
                            <el-table-column label="采购总价" min-width="110">
                                <template #default="scope">
                                    <el-input-number
                                        v-model="scope.row.purchaseTotalAmount"
                                        type="number"
                                        :min="0.01"
                                        :step="0.01"
                                        placeholder="请输入配送总价"
                                        controls-position="right"
                                        style="width: 100%"
                                    />
                                </template>
                            </el-table-column>
                            <el-table-column label="供应商" min-width="130" prop="supplierId">
                                <template #default="scope">
                                    <el-select
                                        placeholder="---供应商---"
                                        v-model="scope.row.supplierId"
                                        filterable 
                                        style="width: 100%"
                                        @change="getSupplierName"
                                    >
                                        <el-option
                                            v-for="item in suppliers"
                                            :key="item.supplierId"
                                            :label="item.supplierOrgName"
                                            :value="item.supplierId"
                                        />
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column label="备注" min-width="160">
                                <template #default="scope">
                                    <el-input v-model="scope.row.remarks" style="width: 100%" />
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="24" style="padding-left: 10px;">
                    <el-form-item label-width="120px" label="要货备注">
                        <el-collapse v-model="activeNames" style="width: 100%;">
                            <div class="collapse-container">
                                <div class="collapse-header" @click="toggleCollapse">
                                    <span></span>
                                    <div style="display: flex;align-items: center;">
                                        <span class="expand-text">{{ isCollapsed ? '展开' : '收起' }}</span>
                                        <img
                                            v-if="isCollapsed"
                                            class="icon-img"
                                            src="https://oss.jtmckj.com/pc/images/pay/arrow-bt.png"
                                        />
                                        <img
                                            v-else
                                            class="icon-img"
                                            src="https://oss.jtmckj.com/pc/images/pay/arrow-top.png"
                                        />
                                    </div>
                                </div>
                            </div>
                            <div v-show="!isCollapsed" class="collapse-content1">
                                <sc-editor
                                    ref="scRemarks"
                                    v-model="entityObj.remarks"
                                    :height="300"
                                    style="width: 100%;"
                                ></sc-editor>
                            </div>
                        </el-collapse>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12" style="padding-left: 10px;">
                    <el-form-item label-width="120px" label="其它费用" prop="otherFee">
                        <el-input-number
                            v-model="entityObj.otherFee"
                            :precision="2"
                            :step="0.01"
                            style="width: 100%"
                            @change="otherFeechange"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12" style="padding-left: 10px;">
                    <el-form-item label-width="120px" label="单据金额" prop="totalAmount">
                        <el-input-number
                            v-model="totalAmount"
                            :step="0.01"
                            :min="0"
                            :precision="2"
                            disabled
                            style="width: 100%"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24" style="margin-left: 10px;">
                    <el-form-item label-width="120px" label="附件">
                        <sc-upload-file
                            v-model="entityObj.applyFile"
                            :objName="'Supply/ApplyOrder'"
                            draggable
                            :uploadType="'OSS'"
                            :bucketName="'jtmc'"
                            :limit="1"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <!-- <el-row>
                <el-col :span="24">
                    <el-form-item label-width="120px" label="备注">
                        <el-input v-model="entityObj.remarks" type="textarea" :rows="2" />
                    </el-form-item>
                </el-col>
            </el-row>-->
        </el-form>

        <template #footer>
            <el-button @click="handleBeforeClose">取 消</el-button>
            <el-button
                v-if="mode != 'show'"
                type="primary"
                :loading="isSaveing"
                @click="materialAddclick(3)"
            >暂 存</el-button>
            <el-button v-if="mode != 'show'" type="primary" @click="materialAddclick(8)">保 存</el-button>
        </template>
        <!-- 添加物料 -->
        <!-- 查看文本备注 -->
        <template>
            <el-dialog
                v-model="notesDialog"
                title="文本备注"
                :width="500"
                :center="true"
                append-to-body
                style="height: 480px"
            >
                <el-row>
                    <div v-html="materialNotes" style="width: 100%"></div>
                </el-row>
                <template #footer>
                    <el-button @click="notesDialog = false">关 闭</el-button>
                </template>
            </el-dialog>
        </template>

        <!-- 物料 -->
        <template>
            <el-dialog
                v-model="materialState"
                title="存在相同的物料，是否与要添加的匹配。"
                :center="true"
                :width="800"
                append-to-body
            >
                <el-row style="margin-bottom: 10px;">
                    <scTable
                        ref="mytable"
                        :data="entityObj.materials"
                        :hidePagination="true"
                        :hideRefresh="true"
                        :hideSetting="true"
                        @row-click="clickRow"
                        :sort-orders="['ascending', 'descending']"
                        @selection-change="selectionChange"
                        row-key="'storeId'"
                        key="'storeId'"
                    >
                        <el-table-column type="selection" min-width="50"></el-table-column>
                        <el-table-column label="物料编码" prop="materialCode" min-width="110"></el-table-column>
                        <el-table-column label="物料名称" prop="materialName" min-width="180"></el-table-column>
                        <el-table-column label="物料规格" prop="materialSpecs" min-width="120"></el-table-column>
                        <el-table-column label="单位" prop="unitName" min-width="150"></el-table-column>
                    </scTable>
                </el-row>
                <template #footer>
                    <el-button @click="materialState = false">取 消</el-button>
                    <el-button type="primary" :loading="isSaveing" @click="setMaterialChoice">确定</el-button>
                </template>
            </el-dialog>
        </template>

        <!-- 预览组件 -->
        <el-image-viewer
            v-if="showImage"
            @close="closeViewer"
            :hide-on-click-modal="true"
            :url-list="srcList"
        />
    </full-screen-dialog>
</template>



<script>
import tool from "@/utils/tool";
import pyconst from "@/api/model/pyconst";
export default {
    emits: ["success", "closed"],
    data() {
        return {
            mode: "Add",
            titleMap: {
                Add: "新增",
                Edit: "编辑",
                Show: "查看",
            },
            entityObj: {
                applyOrderCode: "",
                applyDate: "",
                expectedDate: "",
                storeId: 0,
                storeName: "",
                realName: "",
                mobile: "",
                address: "",
                purchaseUnityId: 0,
                purchaseUnityName: "",
                purchaseRealName: "",
                applyName: "",
                createTime: "",
                remarks: "",
                otherFee: 0.0,
                totalAmount: 0.0,
                protocolFile: "",
                applyOrderItems: [],
                type: 0,
            },
            suppliers: [],
            supplierProps: {
                label: "supplierName",
                value: "supplierId",
            },
            itemsData: [
                {
                    materialCode: "", // 物料编码
                    materialName: "", // 物料名称
                    materialSimpCode: "", // 物料简码
                    materialSpecs: "", // 规格
                    materialTypeId: 0, // 物料类别ID
                    status: 0, // 状态
                    remarks: "", // 备注
                    materialImages: [], // 物料图片列表
                    materialThumbnailImage: "", // 物料缩略图
                    purchaseUnitCode: "", // 采购单位编码
                    purchaseUnitName: "", // 采购单位名称
                    saleUnitCode: "", // 销售单位编码
                    saleUnitName: "", // 销售单位名称
                    stockUnitCode: "", // 库存单位编码
                    stockUnitName: "", // 库存单位名称
                    auxiliaryUnitCode: "", // 辅助单位编码
                    auxiliaryUnitName: "", // 辅助单位名称
                    minStock: 1, // 最小库存
                    isSpecial: false, // 是否特殊物料
                    minDeliveryQty: 0, // 最小配送数量
                    generalRate: 0, // 通用税率
                    incrementRate: 0, // 增值税率
                    materialDetail: "", // 物料详情
                    materialItems: [
                        // 物料子项列表
                        {
                            materialItemId: 0, // 物料子项ID
                            materialItemCode: "", // 物料子项编码
                            materialItemName: "", // 物料子项名称
                            unitCode: "", // 单位编码
                            unitName: "", // 单位名称
                            brandCode: "",
                            brandName: "",
                            unitQty: 0, // 单位数量
                            isMinUnit: false, // 是否最小单位
                            price: 0, // 价格
                            minApplyQty: 0, // 最小申请数量
                        },
                    ],
                    deliveryProtocols: [
                        // 配送协议列表
                        {
                            storeId: 0, // 门店ID
                            unitCode: "", // 单位编码
                            price: 0, // 价格
                            isDisposable: false, // 是否一次性
                            brandCode: "",
                            brandName: "",
                        },
                    ],
                    purchaseProtocols: [
                        // 采购协议列表
                        {
                            supplierId: 0, // 供应商ID
                            unitCode: "", // 单位编码
                            price: 0, // 价格
                            isDisposable: false, // 是否一次性
                            brandCode: "",
                            brandName: "",
                        },
                    ],
                },
            ],
            tb: [],
            checkedDetail: [],
            order: 0,
            orgType: 2,
            orgId: 0,
            //预览图片
            previewUrl: [],
            //预览图片列表
            srcList: [],
            showImage: false,
            materialState: false,
            applyOrderState: false,
            storeQueryList: {},
            applyOrderQueryList: {},
            storeState: false,
            queryList: {},
            visible: false,
            isSaveing: false,
            needSaveFlag: false,
            purchaseUnityDisabledState: false,
            purchaseUnityProps: {
                label: "purchaseUnityName",
                value: "purchaseUnityId",
            },
            //验证规则
            rules: {
                //applyOrderCode: [{ required: true, type: "string", message: "请填写" },],
                applyDate: [
                    { required: true, type: "string", message: "请填写" },
                ],
                storeId: [
                    { required: true, type: "number", message: "请填写" },
                ],
                purchaseUnityId: [
                    { required: true, type: "number", message: "请填写" },
                ],
                realName: [
                    { required: true, type: "string", message: "请填写" },
                ],
                mobile: [{ required: true, type: "string", message: "请填写" }],
                address: [
                    { required: true, type: "string", message: "请填写" },
                ],

                purchaseRealName: [
                    { required: true, type: "string", message: "请填写" },
                ],
                purchaseMobile: [
                    { required: true, type: "string", message: "请填写" },
                ],

                applyName: [
                    { required: true, type: "string", message: "请填写" },
                ],
                createTime: [
                    { required: true, type: "string", message: "请填写" },
                ],
                // applyOrderItems: [
                //     {
                //         required: true,
                //         type: "array",
                //         message: "请填写",
                //         trigger: "change",
                //     },
                // ],
            },
            props: {
                label: "supplierName",
                value: "supplierId",
            },
            storeProps: {
                label: "storeOrgName",
                value: "storeId",
            },
            materialProps: {
                label: "materialCode",
                value: "materialId",
                items: "materialItems",
            },
            materialTypeTree: [],
            optionsBrand: [],
            optionsUnit: [],
            optionsPurchaseUnity: [],
            activeNames: [],
            isCollapsed: true, // 初始状态为收起
            defaultTime: [
                new Date(2000, 1, 1, 0, 0, 0),
                new Date(2000, 2, 1, 23, 59, 59),
            ],
            notesDialog: false,
            materialNotes: "",
            supplier: [],
            selectionRows: [],
            materialIndex: 0,
        };
    },
    computed: {
        totalAmount() {
            let materialFee=0;
            let otherFee=0;
            if(this.entityObj.applyOrderItems&&this.entityObj.applyOrderItems.length>0){
                materialFee=  this.entityObj.applyOrderItems.reduce((sum, item) => sum + item.applyTotalAmount, 0)
            }
            if(this.entityObj.otherFee){
                otherFee=this.entityObj.otherFee
            }
            const totalAmount = materialFee + otherFee;
            return totalAmount;
        },
    },
    methods: {
        otherFeechange() {
            this.entityObj.totalAmount += this.entityObj.otherFee;
        },
        getSupplierName(value) {
            // 选择时拿到的 id
            console.log("选中的ID:", value);
        },
        handleSelectionChanged(selectionRows) {
            this.setMaterialChoice();
        },
        //设置备注栏的行数
        computedRows(rowRemarks) {
            // 计算所需的行数
            const lineRow = 10; // 每行的长度
            return rowRemarks?.length / lineRow == 0
                ? 1
                : Math.ceil(rowRemarks?.length / lineRow);
        },
        //图片预览
        handlePreview(row) {
            console.log("row", row.materialImages);
            if (!row.materialImages || row.materialImages.length == 0) {
                return;
            }
            this.previewUrl = row.materialImages[0]; // 设置当前预览的图片 URL
            this.srcList = row.materialImages; // 设置预览列表
            this.showImage = true; // 显示 el-image
        },
        closeViewer() {
            this.showImage = false;
        },
        //显示=
        async open(mode = "Add") {
            if (mode == "Add" && this.orgType == 2) {
                var returnValue = await this.$API.auth.GetProcessApi.get(
                    "store/current"
                );

                if (returnValue.status == 200) {
                    this.entityObj.storeName = returnValue.response.storeName;
                    this.entityObj.storeId = returnValue.response.storeId;
                    this.entityObj.realName = returnValue.response.realName;
                    this.entityObj.mobile = returnValue.response.mobile;
                    this.entityObj.address = returnValue.response.address;
                    console.log("returnValue.status", returnValue.status);
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            }
            if (mode == "Edit") {
                this.orgType = 2;
            }
            this.mode = mode;
            this.visible = true;
            return this;
        },
        handleBeforeClose() {
            this.$confirm("信息未保存,确定要关闭吗？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    this.visible = false;
                })
                .catch(() => {
                    // 用户点击了取消按钮，不执行关闭
                });
        },
        //添加
        async materialAddclick(status) {
            this.entityObj.applyOrderItems.forEach((item) => {
                if (item.materialName && !item.materialCode) {
                    var unitCode = item.unitCode;
                    var unit = this.optionsUnit.find(
                        (option) => option.value === unitCode
                    );
                    item.unitName = unit.label;
                }
            });

            this.entityObj.status = status;
            try {
                const response = await this.$API.auth.PostProcessApi.post(
                    "apply-order/jc-apply-create",
                    this.entityObj // 传递数组
                );
                console.log(response);
                if (response.status === 200) {
                    console.log("操作操作", response.data);
                    this.$message.success("操作成功");
                    this.entityObj.applyOrderItems = response.response;
                    this.$emit("fatherMethod");
                    this.isSaveing = false;
                    this.visible = false;
                } else {
                    this.$message.error("操作失败: " + response.msg);
                }
            } catch (error) {
                this.$message.error("请求失败: " + error.message);
            }
        },
        //表单注入数据
        async setData(data) {
            this.entityObj = data;
         
            // // 检查 data 是否存在并且包含 applyOrderItems 属性
            // if (
            //     data &&
            //     data.applyOrderItems &&
            //     Array.isArray(data.applyOrderItems)
            // ) {
            //     var purchasesList = [];
            //     data.applyOrderItems.forEach((p) => {
            //         if (p.purchases && Array.isArray(p.purchases)) {
            //             p.purchases.forEach((x) => {
            //                 console.log(
            //                     "供应商ID:",
            //                     x.supplierId,
            //                     x.supplierName
            //                 );
            //                 purchasesList.push({
            //                     supplierId: x.supplierId,
            //                     supplierName: x.supplierName,
            //                 });
            //             });
            //         }
            //     });

            // }

            if(!this.entityObj.applyOrderId){
                this.entityObj.applyName = tool.data.get("USER_INFO").Name;
                this.entityObj.applyDate = this.formatDate(new Date(), 1);
                this.entityObj.createTime = this.formatDate(new Date());
            }

            this.orgType = tool.data.get("USER_INFO").AccountType;
            if (this.orgType == 1) {
                await this.getPurchaseUnity("purchase-unity/current");
            }
        },
        async initOptions() {
            try {
                var returnValue = await this.$API.auth.GetProcessApi.get(
                    `purchase-unity-supplier-relation/${this.orgId}`,
                    {}
                );
                if (returnValue.status == 200) {
                    this.suppliers = returnValue.response;
                    console.log("this.suppliers", this.suppliers);
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }

            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "material-type/tree",
                    { status: 1 }
                );
                if (returnValue.status == 200) {
                    this.materialTypeTree = returnValue.response;
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }

            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "base-dictionary/dic-options",
                    { ParentBaseDictionaryCodes: ["001", "002"] }
                );

                if (returnValue.status == 200) {
                    this.optionsBrand = returnValue.response.find(
                        (p) => p.code == "001"
                    ).optionsDetails;
                    this.optionsUnit = returnValue.response.find(
                        (p) => p.code == "002"
                    ).optionsDetails;
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
        async getPurchaseUnity(url) {
            //采购单位列表
            var returnValue = await this.$API.auth.GetProcessApi.get(url);
            if (returnValue.status == 200) {
                this.entityObj.purchaseUnityId =
                    returnValue.response.purchaseUnityId;
                this.entityObj.purchaseUnityName =
                    returnValue.response.purchaseUnityName;
                this.entityObj.purchaseRealName = returnValue.response.realName;
                this.entityObj.purchaseMobile = returnValue.response.mobile;
                this.entityObj.purchaseAddress = returnValue.response.address;
            } else {
                this.$message.error("操作失败:" + returnValue.msg);
            }
        },
        async supplierSelectProcess(row, rowData) {
            console.log("row", row);
            console.log("rowData", rowData);
            row.supplier.supplier = {};

            if (rowData) {
                row.supplier = {
                    supplierId: rowData.supplierId,
                    supplierName: rowData.supplierName,
                };
                row.supplierId = rowData.supplierId;
            }
        },
        deleteRow(index) {
            this.entityObj.applyOrderItems.splice(index, 1);
        },
        deleteTempRow(index) {
            this.entityObj.applyOrderTempItems.splice(index, 1);
        },
        //匹配输入物料
        async handleMaterial(row, index) {
            if (row.materialName) {
                this.materialIndex = index;
                this.isSaveing = true;
                var verifyValue = await this.$API.auth.PostProcessApi.post(
                    "material/is-exists-materials",
                    row
                );
                if (verifyValue.status == 200) {
                    var list = verifyValue.response;
                    this.entityObj.materials = list;

                    if (list && list?.length > 0) {
                        this.materialState = true;
                        this.isSaveing = false;
                        return;
                    }
                }
            }
        },
        //表格选择后回调事件
        selectionChange(selection) {
            this.selectionRows = selection;
        },
        //选择匹配的商品
        setMaterialChoice() {
            if (!this.selectionRows || this.selectionRows.length == 0) {
                this.$message.error("请选择要匹配的商品");
                return;
            }

            if (this.selectionRows.length > 1) {
                this.$message.error("只能选择一个商品");
                return;
            }

            this.entityObj.applyOrderItems[this.materialIndex].materialId= this.selectionRows[0].materialId;
            this.entityObj.applyOrderItems[this.materialIndex].materialItemId= this.selectionRows[0].materialItemId;
            this.entityObj.applyOrderItems[this.materialIndex].materialCode= this.selectionRows[0].materialCode;
            this.entityObj.applyOrderItems[this.materialIndex].materialSimpCode= this.selectionRows[0].materialSimpCode;
            this.entityObj.applyOrderItems[this.materialIndex].materialName=this.selectionRows[0].materialName;
            this.entityObj.applyOrderItems[this.materialIndex].materialSpecs=this.selectionRows[0].materialSpecs;
            this.entityObj.applyOrderItems[this.materialIndex].materialTypeId= this.selectionRows[0].materialTypeId;
            this.entityObj.applyOrderItems[this.materialIndex].materialTypeName=this.selectionRows[0].materialTypeName;
            this.entityObj.applyOrderItems[this.materialIndex].unitCode=this.selectionRows[0].unitCode;
            this.entityObj.applyOrderItems[this.materialIndex].unitName= this.selectionRows[0].unitName;
            
            this.materialState = false;
        },
        async addApplyOrder() {
            if (!this.entityObj.storeId) {
                this.$message.error("请先选择要货单位");
                return;
            }

            // if (!this.entityObj.purchaseUnityId) {
            //     this.$message.error("请先选择采购单位");
            //     return;
            // }

            // 查询是否有历史要货记录，有的话默认最近一天的记录
            const returnValue = await this.$API.auth.PostProcessApi.post(
                "apply-order/applyOrder-last-dates",
                { storeId: this.entityObj.storeId }
            );
            // if(!returnValue.response){
            //     this.$message.error("暂无历史要货记录");
            //     return;
            // }
            this.applyOrderState = true;
            this.applyOrderQueryList = {
                applyDates: returnValue.response,
                storeId: this.entityObj.storeId,
            };
            if (
                this.orgType == 1 ||
                (this.entityObj.applyOrderId > 0 && this.entityObj.status != 3)
            ) {
                this.applyOrderQueryList = {
                    applyDates: returnValue.response,
                    storeId: this.entityObj.storeId,
                    purchaseUnityId: this.entityObj.purchaseUnityId,
                };
            }
            this.$nextTick(() => {
                this.$refs.scApplyOrderChoice.opBindData();
            });
        },
        async setApplyOrderChoice() {
            if (!this.entityObj.storeId) {
                this.$message.error("请先选择要货单位");
                return;
            }

            let applyOrders = this.$refs.scApplyOrderChoice.selectionRows;
            let materialIds = [];

            applyOrders.map((p) => {
                materialIds.push(p.materialId);
            });
            const returnValue = await this.$API.auth.PostProcessApi.post(
                "delivery-protocol/material-pages",
                {
                    pageIndex: 1,
                    pageSize: 9999,
                    storeId: this.entityObj.storeId,
                    materialIds: materialIds,
                }
            );
            if (returnValue.status == 200) {
                const materials = returnValue.response.data;
                console.log("applyOrders", applyOrders);
                applyOrders.map((p) => {
                    if (p.applyOrderItemType == 0) {
                        const material = materials.find(
                            (z) =>
                                z.materialId == p.materialId &&
                                z.purchaseUnityId == p.purchaseUnityId
                        );

                        if (material) {
                            const materialItem =
                                material.materialItems.length > 0
                                    ? material.materialItems[0]
                                    : [];
                            this.entityObj.applyOrderItems.push({
                                purchaseUnityId: p.purchaseUnityId,
                                materialId: material.materialId,
                                materialCode: material.materialCode,
                                materialName: material.materialName,
                                materialSpecs: material.materialSpecs,
                                materialSimpCode: material.materialSimpCode,
                                materialTypeId: material.materialTypeId,
                                materialTypeName: material.materialTypeName,
                                purchaseTotalAmount: p.price,
                                qty:
                                    p.qty >= materialItem?.minApplyQty
                                        ? p.qty
                                        : materialItem?.minApplyQty,
                                minQty: materialItem?.minApplyQty
                                    ? materialItem?.minApplyQty
                                    : 1,
                                applyTotalAmout: p.totalAmount,
                                remarks: p.remarks,
                                materialItemId: p.materialItemId,
                                materialItems: material.materialItems,
                                applyOrderItemType: 0,
                            });
                        }
                    } else {
                        if (
                            !this.entityObj.applyOrderTempItems ||
                            this.entityObj.applyOrderTempItems.length == 0
                        ) {
                            this.entityObj.applyOrderTempItems = [];
                        }

                        this.entityObj.applyOrderTempItems.push({
                            purchaseUnityId: p.purchaseUnityId,
                            materialTypeId: 0,
                            MaterialId: 0,
                            MaterialItemId: 0,
                            materialCode: "",
                            materialName: p.materialName,
                            unitName: p.unitName,
                            materialSpecs: p.materialSpecs,
                            materialTypeName: "",
                            qty: p.qty,
                            totalAmount: 0,
                            remarks: p.remarks,
                            applyOrderItemType: 1,
                        });
                    }
                });
                console.log(1111);
                this.applyOrderState = false;
            }
        },
        purchaseUnityChange(value) {
            this.entityObj.purchaseRealName = this.optionsPurchaseUnity.find(
                (p) => p.purchaseUnityId == value
            ).realName;
            this.entityObj.purchaseMobile = this.optionsPurchaseUnity.find(
                (p) => p.purchaseUnityId == value
            ).mobile;
        },
        storeSelectProcess(rowData) {
            this.setStore(rowData);
        },
        setStore(rowData) {
            this.entityObj.store = rowData;
            this.entityObj.storeName = rowData.storeName;
            this.entityObj.storeOrgType=rowData.storeOrgType;
            this.entityObj.storeId = rowData.storeId;
            this.entityObj.realName = rowData.realName;
            this.entityObj.mobile = rowData.mobile;
            this.entityObj.address = rowData.address;
        },
        async purchaseUnitySelectProcess(rowData) {
            if (
                this.entityObj.applyOrderItems &&
                this.entityObj.applyOrderItems.length > 0
            ) {
                this.$confirm("是否修改采购单位,要货清单会被清空？", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                    .then(() => {
                        this.entityObj.applyOrderItems = [];
                        this.setPurchaseUnity(rowData);
                    })
                    .catch(() => {});
            }
            this.setPurchaseUnity(rowData);
        },
        setPurchaseUnity(rowData) {
            if (rowData) {
                this.entityObj.purchaseUnityId = rowData.purchaseUnityId;
                this.entityObj.purchaseUnityName = rowData.purchaseUnityName;
                this.entityObj.realName = rowData.realName;
                this.entityObj.mobile = rowData.mobile;
                this.entityObj.address = rowData.address;
                this.entityObj.purchaseUnitys = {
                    purchaseUnityId: rowData.purchaseUnityId,
                    purchaseUnityName: rowData.purchaseUnityName,
                };
            }
        },
        resetSearch() {
            this.queryList = {};
        },
        formatDate(date, type = 0) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, "0");
            const day = String(date.getDate()).padStart(2, "0");
            const hours = String(date.getHours()).padStart(2, "0");
            const minutes = String(date.getMinutes()).padStart(2, "0");
            const seconds = String(date.getSeconds()).padStart(2, "0");

            return type == 0
                ? `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
                : `${year}-${month}-${day}`;
        },
        toggleCollapse() {
            this.isCollapsed = !this.isCollapsed; // 切换展开/收起状态
        },
        //显示文本备注
        onShowNotes(notes) {
            console.log("显示文本备注", notes);
            this.notesDialog = true;
            this.materialNotes = notes;
        },
        handleAddDetails() {
            if (
                !this.entityObj.applyOrderItems ||
                this.entityObj.applyOrderItems.length == 0
            ) {
                this.entityObj.applyOrderItems = [];
            }
            let obj = {
                purchaseUnityId: null,
                materialId: null,
                materialCode: null,
                materialSimpCode: null,
                materialName: null,
                materialSpecs: null,
                materialTypeId: null,
                materialTypeName: null,
                materialImages: null,
                price: null,
                qty: null,
                totalAmount: null,
                remarks: null,
                materialItemId: null,
                materialItems: null,
                applyOrderItemType: null,
            };
            this.entityObj.applyOrderItems.push(obj);
        },
        //获取供应商
        async supplierSelectProcess(rowData) {
            this.entityObj.supplier = {
                supplierId: rowData.supplierId,
                supplierName: rowData.supplierName,
            };
            this.entityObj.supplierId = rowData.supplierId;
        },
        handleDetailSelectionChange(selection) {
            this.tb = selection;
        },
        rowClassName({ row, rowIndex }) {
            row.tb = rowIndex + 1;
        },
        //删除选择行
        handleDeleteDetails() {
            if (this.tb.length === 0) {
                this.$message.warning("请选择要删除的行");
                return;
            }

            // 过滤掉选中的行
            this.entityObj.applyOrderItems =
                this.entityObj.applyOrderItems.filter(
                    (row) => !this.tb.includes(row)
                );
            this.$message.success("删除成功");
        },

        handleDeleteAllDetails() {
            this.itemsData = []; // 清空所有行
        },
    },
    async mounted() {
        this.orgType = tool.data.get("USER_INFO").AccountType;
        this.orgId = tool.data.get("USER_INFO").OrgId;
        await this.initOptions();
    },
};
</script>

<style lang="scss" scoped>
.add-material-but {
    text-align: center;
    width: 80px;
    height: 28px;
    background: #ffffff;
    border-radius: 4px;
    border: 1px solid #318cf2;
    line-height: 28px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    font-size: 14px;
    color: #318cf2;
}

.add-order-but {
    margin-left: 10px;
    text-align: center;
    width: 160px;
    height: 28px;
    background: #ffffff;
    border-radius: 4px;
    border: 1px solid #318cf2;
    line-height: 28px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    font-size: 14px;
    color: #318cf2;
}

.add-temporary-but {
    text-align: center;
    width: 100px;
    height: 28px;
    background: #ffffff;
    border-radius: 4px;
    border: 1px solid #318cf2;
    line-height: 28px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    font-size: 14px;
    color: #318cf2;
}

.del-temp-but {
    text-align: center;
    width: 46px;
    height: 24px;
    background: #ffffff;
    border-radius: 4px;
    border: 1px solid #318cf2;
    font-family: Microsoft YaHei;
    font-weight: 400;
    font-size: 14px;
    color: #318cf2;
}

.w25pr30 {
    width: 25%;
    padding-right: 30px;
}
.w25 {
    width: 25%;
}

::v-deep .el-form-item__label {
    width: 100px !important;
    justify-content: flex-start;
}

.collapse-container {
    border-top: 1px solid #f6f6f6;
    border-bottom: 1px solid #f6f6f6;
    padding: 10px 10px 10px 0;
    margin-bottom: 10px;
}

.collapse-header {
    display: flex;
    justify-content: space-between;
    cursor: pointer;
    padding: 5px;
    padding-left: 0;
    font-weight: bold;
    font-size: 12px;
}
.collapse-content1 {
    padding: 10px;
    background: #f2f2f2;
}
.icon-img {
    width: 16px;
    height: 10px;
    margin-left: 5px;
}
</style>

<style scoped>
.el-upload--picture-card {
    width: 50px;
    height: 50px;
}
.el-upload {
    width: 50px;
    height: 50px;
    line-height: 50px;
}
.el-upload-list--picture-card .el-upload-list__item {
    width: 50px;
    height: 50px;
    line-height: 50px;
}
.el-upload-list--picture-card .el-upload-list__item-thumbnail {
    width: 50px;
    height: 50px;
    line-height: 50px;
}
.el-table .info-row > td {
    background: #e4e7ed;
    user-select: none; /* 禁用文本选择 */
    pointer-events: none; /* 禁用鼠标事件 */
}
</style>
